package com.chuhe.starry.websocket;


import com.alibaba.fastjson.JSON;
import com.chuhe.common.domain.dto.MessageSendDto;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component("messageHandler")
@Slf4j
public class MessageHandler<T> {

    private static final String MESSAGE_TOPIC = "message.topic";

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ChannelContextUtils channelContextUtils;

    /**
     * 集群推送消息
     * @Author: 楚河
     * @Date: 2025-05-22 17:16
     */
    @PostConstruct//当 Spring Bean 初始化完成后，自动执行这个方法。
    public void lisMessage() {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.addListener(MessageSendDto.class, (MessageSendDto, sendDto) -> {
            log.info("收到广播消息:{}", JSON.toJSONString(sendDto));
            channelContextUtils.sendMessage(sendDto);
        });
    }

    /**
     * Redis 会自动将消息推送给所有订阅了 message.topic 主题的应用实例。
     * @Author: 楚河
     * @Date: 2025-05-22 15:30
     */
    public void sendMessage(MessageSendDto sendDto) {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.publish(sendDto);
    }
}
